/**
 *    Copyright 2009-2015 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.datasource.unpooled;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

import javax.sql.DataSource;

import org.apache.ibatis.io.Resources;

/**
 * @author Clinton Begin
 * @author Eduardo Macarron
 */
/**
 * 没有池化的数据源
 */
public class UnpooledDataSource implements DataSource {
	/**
	 * 驱动类加载器
	 */
	private ClassLoader driverClassLoader;
	// 作为可选项,你可以传递数据库驱动的属性。要这样做,属性的前缀是以“driver.”开 头的,例如
	// driver.encoding=UTF8
	/**
	 * 驱动连接属性
	 */
	private Properties driverProperties;
	/**
	 * 所有已注册的驱动，仅仅用于识别驱动在DriverManager中是否已经被加载进来了
	 */
	private static Map<String, Driver> registeredDrivers = new ConcurrentHashMap<String, Driver>();
	/**
	 * 当前使用的驱动
	 */
	private String driver;
	/**
	 * url
	 */
	private String url;
	/**
	 * 用户名
	 */
	private String username;
	/**
	 * 密码
	 */
	private String password;
	/**
	 * 是否自动提交
	 */
	private Boolean autoCommit;
	/**
	 * 默认的事务隔离级别
	 */
	private Integer defaultTransactionIsolationLevel;
	/**
	 * 静态代码块,当类加载的时候，就从DriverManager中获取所有的驱动信息，放到当前维护的Map中
	 */
	static {
		Enumeration<Driver> drivers = DriverManager.getDrivers();
		while (drivers.hasMoreElements()) {
			Driver driver = drivers.nextElement();
			registeredDrivers.put(driver.getClass().getName(), driver);
		}
	}

	public UnpooledDataSource() {
	}

	/**
	 * 构造器
	 * 
	 * @param driver
	 *            驱动
	 * @param url
	 *            url
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 */
	public UnpooledDataSource(String driver, String url, String username, String password) {
		this.driver = driver;
		this.url = url;
		this.username = username;
		this.password = password;
	}

	/**
	 * 构造器
	 * 
	 * @param driver
	 *            驱动
	 * @param url
	 *            url
	 * @param driverProperties
	 *            驱动属性
	 */
	public UnpooledDataSource(String driver, String url, Properties driverProperties) {
		this.driver = driver;
		this.url = url;
		this.driverProperties = driverProperties;
	}

	/**
	 * 构造器
	 * 
	 * @param driverClassLoader
	 *            驱动加载器
	 * @param driver
	 *            驱动
	 * @param url
	 *            url
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 */
	public UnpooledDataSource(ClassLoader driverClassLoader, String driver, String url, String username,
			String password) {
		this.driverClassLoader = driverClassLoader;
		this.driver = driver;
		this.url = url;
		this.username = username;
		this.password = password;
	}

	/**
	 * 构造器
	 * 
	 * @param driverClassLoader
	 *            驱动加载器
	 * @param driver
	 *            驱动
	 * @param url
	 *            url
	 * @param driverProperties
	 *            驱动属性
	 */
	public UnpooledDataSource(ClassLoader driverClassLoader, String driver, String url, Properties driverProperties) {
		this.driverClassLoader = driverClassLoader;
		this.driver = driver;
		this.url = url;
		this.driverProperties = driverProperties;
	}

	@Override
	public Connection getConnection() throws SQLException {
		return doGetConnection(username, password);
	}

	@Override
	public Connection getConnection(String username, String password) throws SQLException {
		return doGetConnection(username, password);
	}

	@Override
	public void setLoginTimeout(int loginTimeout) throws SQLException {
		DriverManager.setLoginTimeout(loginTimeout);
	}

	@Override
	public int getLoginTimeout() throws SQLException {
		return DriverManager.getLoginTimeout();
	}

	@Override
	public void setLogWriter(PrintWriter logWriter) throws SQLException {
		DriverManager.setLogWriter(logWriter);
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		return DriverManager.getLogWriter();
	}

	/**
	 * 得到驱动类加载器
	 * 
	 * @return
	 */
	public ClassLoader getDriverClassLoader() {
		return driverClassLoader;
	}

	/**
	 * 设置驱动类加载器
	 * 
	 * @param driverClassLoader
	 */
	public void setDriverClassLoader(ClassLoader driverClassLoader) {
		this.driverClassLoader = driverClassLoader;
	}

	/**
	 * 得到驱动属性
	 * 
	 * @return
	 */
	public Properties getDriverProperties() {
		return driverProperties;
	}

	/**
	 * 设置驱动属性
	 * 
	 * @param driverProperties
	 */
	public void setDriverProperties(Properties driverProperties) {
		this.driverProperties = driverProperties;
	}

	/**
	 * 得到驱动
	 * 
	 * @return
	 */
	public String getDriver() {
		return driver;
	}

	/**
	 * 设置驱动
	 * 
	 * @param driver
	 */
	public synchronized void setDriver(String driver) {
		this.driver = driver;
	}

	/**
	 * 得到url
	 * 
	 * @return
	 */
	public String getUrl() {
		return url;
	}

	/**
	 * 设置url
	 * 
	 * @param url
	 */
	public void setUrl(String url) {
		this.url = url;
	}

	/**
	 * 得到用户名
	 * 
	 * @return
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * 设置用户名
	 * 
	 * @param username
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * 得到密码
	 * 
	 * @return
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * 设置密码
	 * 
	 * @param password
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * 是否自动提交
	 * 
	 * @return
	 */
	public Boolean isAutoCommit() {
		return autoCommit;
	}

	/**
	 * 设置是否自动提交
	 * 
	 * @param autoCommit
	 */
	public void setAutoCommit(Boolean autoCommit) {
		this.autoCommit = autoCommit;
	}

	/**
	 * 得到默认的事务隔离级别
	 * 
	 * @return
	 */
	public Integer getDefaultTransactionIsolationLevel() {
		return defaultTransactionIsolationLevel;
	}

	/**
	 * 设置默认的事务隔离级别
	 * 
	 * @param defaultTransactionIsolationLevel
	 */
	public void setDefaultTransactionIsolationLevel(Integer defaultTransactionIsolationLevel) {
		this.defaultTransactionIsolationLevel = defaultTransactionIsolationLevel;
	}

	/**
	 * 得到连接
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return
	 * @throws SQLException
	 */
	private Connection doGetConnection(String username, String password) throws SQLException {
		// 这里通过url加Properties来获取连接，是因为可以在配置文件中配置数据库连接的信息，比如编码之类的
		Properties props = new Properties();
		if (driverProperties != null) {
			props.putAll(driverProperties);
		}
		if (username != null) {
			props.setProperty("user", username);
		}
		if (password != null) {
			props.setProperty("password", password);
		}
		return doGetConnection(props);
	}

	/**
	 * 得到连接
	 * 
	 * @param properties
	 *            属性文件
	 * @return
	 * @throws SQLException
	 */
	private Connection doGetConnection(Properties properties) throws SQLException {
		// 初始化驱动信息
		initializeDriver();
		// 属性的前缀是以“driver.”开 头的,它 是 通 过
		// DriverManager.getConnection(url,driverProperties)方法传递给数据库驱动
		// 从DriverManager中获取数据库连接
		Connection connection = DriverManager.getConnection(url, properties);
		// 配置连接信息，自动提交以及事务隔离级别
		configureConnection(connection);
		return connection;
	}

	/**
	 * 驱动初始化
	 * 
	 * @throws SQLException
	 */
	private synchronized void initializeDriver() throws SQLException {
		// 如果没有包含在已注册Map中，则需要将该驱动加载进来
		if (!registeredDrivers.containsKey(driver)) {
			Class<?> driverType;
			try {
				// 加载数据库连接驱动
				if (driverClassLoader != null) {
					driverType = Class.forName(driver, true, driverClassLoader);
				} else {
					// Resources为MyBatis内置的资源工具类，该方法依次尝试从多个ClassLoader中获取Class类，顺序为：配置的classLoader，默认的defaultClassLoader，当前线程的getContextClassLoader，当前类的getClass().getClassLoader()，系统的systemClassLoader
					driverType = Resources.classForName(driver);
				}
				// DriverManager requires the driver to be loaded via the system
				// ClassLoader.
				// http://www.kfu.com/~nsayer/Java/dyn-jdbc.html
				// 创建驱动实例
				Driver driverInstance = (Driver) driverType.newInstance();
				// 注册到DriverManager中，用于创建数据库连接
				DriverManager.registerDriver(new DriverProxy(driverInstance));
				// 放到已注册Map中
				registeredDrivers.put(driver, driverInstance);
			} catch (Exception e) {
				throw new SQLException("Error setting driver on UnpooledDataSource. Cause: " + e);
			}
		}
	}

	/**
	 * 配置连接
	 * 
	 * @param conn
	 * @throws SQLException
	 */
	private void configureConnection(Connection conn) throws SQLException {
		if (autoCommit != null && autoCommit != conn.getAutoCommit()) {
			// 如果已开启了事务，则可以将自动提交关闭
			conn.setAutoCommit(autoCommit);
		}
		if (defaultTransactionIsolationLevel != null) {
			// 设置事务隔离级别
			conn.setTransactionIsolation(defaultTransactionIsolationLevel);
		}
	}

	/**
	 * 驱动代理
	 *
	 */
	private static class DriverProxy implements Driver {
		private Driver driver;

		DriverProxy(Driver d) {
			this.driver = d;
		}

		@Override
		public boolean acceptsURL(String u) throws SQLException {
			return this.driver.acceptsURL(u);
		}

		@Override
		public Connection connect(String u, Properties p) throws SQLException {
			return this.driver.connect(u, p);
		}

		@Override
		public int getMajorVersion() {
			return this.driver.getMajorVersion();
		}

		@Override
		public int getMinorVersion() {
			return this.driver.getMinorVersion();
		}

		@Override
		public DriverPropertyInfo[] getPropertyInfo(String u, Properties p) throws SQLException {
			return this.driver.getPropertyInfo(u, p);
		}

		@Override
		public boolean jdbcCompliant() {
			return this.driver.jdbcCompliant();
		}

		// @Override only valid jdk7+
		public Logger getParentLogger() {
			return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
		}
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		throw new SQLException(getClass().getName() + " is not a wrapper.");
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		return false;
	}

	// @Override only valid jdk7+
	public Logger getParentLogger() {
		// requires JDK version 1.6
		return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
	}

}
